package com.edu.system.service.impl;

import cn.hutool.core.date.DateUtil;
import com.edu.common.utils.ListUtils;
import com.edu.system.domain.TClass;
import com.edu.system.domain.TClassGroup;
import com.edu.system.domain.TClassroom;
import com.edu.system.domain.THighlights;
import com.edu.system.domain.TNotice;
import com.edu.system.domain.req.PublishDTO;
import com.edu.system.mapper.THighlightsMapper;
import com.edu.system.service.ITClassGroupService;
import com.edu.system.service.ITClassroomService;
import com.edu.system.service.ITHighlightsService;
import com.edu.system.service.ITNoticeService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.edu.common.utils.DateUtils;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.edu.system.mapper.TPublishClassMapper;
import com.edu.system.domain.TPublishClass;
import com.edu.system.service.ITPublishClassService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 发布-班级关系Service业务层处理
 * 
 * @author xxxx
 * @date 2023-12-27
 */
@Service
public class TPublishClassServiceImpl implements ITPublishClassService 
{
    @Autowired
    private TPublishClassMapper tPublishClassMapper;
    @Resource
    private ITClassGroupService classGroupService;
    @Resource
    private ITNoticeService itNoticeService;
    @Resource
    private ITHighlightsService itHighlightsService;
    @Resource
    private THighlightsMapper tHighlightsMapper;
    @Resource
    private ITClassroomService itClassroomService;

    // 1通知 2校园风采
    public static Integer publish_type_notice=1;
    public static Integer publish_type_high=2;
    /**
     * 查询发布-班级关系
     * 
     * @param id 发布-班级关系主键
     * @return 发布-班级关系
     */
    @Override
    public TPublishClass selectTPublishClassById(Long id)
    {
        return tPublishClassMapper.selectTPublishClassById(id);
    }

    @Override
    public List<TPublishClass> selectByIds(Long[] ids) {
        return tPublishClassMapper.selectByIds(ids);
    }

    /**
     * 查询发布-班级关系列表
     * 
     * @param tPublishClass 发布-班级关系
     * @return 发布-班级关系
     */
    @Override
    public List<TPublishClass> selectTPublishClassList(TPublishClass tPublishClass)
    {
        List<TPublishClass> list = tPublishClassMapper.selectTPublishClassList(tPublishClass);
        if (CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }

        List<Long> noticeIds = list.stream().filter(a -> a.getType().equals(publish_type_notice))
            .map(TPublishClass::gettId).collect(Collectors.toList());
        List<Long> highIds = list.stream().filter(a -> a.getType().equals(publish_type_high))
            .map(TPublishClass::gettId).collect(Collectors.toList());
        List<Long> classIds = list.stream().map(TPublishClass::getClassId).collect(Collectors.toList());

        Map<Long, TNotice> noticeMap = itNoticeService.listByIds(noticeIds, null)
            .stream()
            .collect(Collectors.toMap(TNotice::getId, a -> a));
        Map<Long, THighlights> highMap = itHighlightsService.listByIds(highIds)
            .stream()
            .collect(Collectors.toMap(THighlights::getId, a -> a));
        Map<Long, TClassroom> classMap = itClassroomService.selectClassroomMap(classIds);

        for(TPublishClass c : list){
            if (c.getType().equals(publish_type_notice)){
                TNotice notice = noticeMap.getOrDefault(c.gettId(), new TNotice());
                c.setTitle(notice.getTitle());
                c.setStartEndTime(getStartEndTime(notice.getNoticeStartTime(), notice.getNoticeEndTime()));
            } else {
                THighlights h = highMap.getOrDefault(c.gettId(), new THighlights());
                c.setTitle(h.getTitle());
                c.setStartEndTime(getStartEndTime(h.getStartTime(), h.getEndTime()));
            }
            TClassroom room = classMap.getOrDefault(c.getClassId(), new TClassroom());
            c.setClassName(room.getName());

            if (c.getType().equals(1) && c.getNoticeType().equals(2)){
                c.setType(99);
            }
        }
        return list;
    }

    private String getStartEndTime(Date s, Date e) {
        if (s != null && e != null){
            return DateUtil.formatDate(s) + " ~ " + DateUtil.formatDate(e);
        }
        return "";
    }

    /**
     * 新增发布-班级关系
     * 
     * @param tPublishClass 发布-班级关系
     * @return 结果
     */
    @Override
    public int insertTPublishClass(TPublishClass tPublishClass)
    {
        tPublishClass.setCreateTime(DateUtils.getNowDate());
        return tPublishClassMapper.insertTPublishClass(tPublishClass);
    }

    @Override
    public void saveUnique(TPublishClass t) {
        List<TPublishClass> list = this.selectTPublishClassList(t);
        if (CollectionUtils.isEmpty(list)){
            this.insertTPublishClass(t);
        }
    }

    @Transactional
    @Override
    public void savePublishClass(PublishDTO dto) {
        // 删除关系
        this.deleteTPublishClass(dto.getIds(), dto.getPublishType());

        // 更新开始 结束时间
        dto.getIds().forEach(id ->{
            if (dto.getPublishType().equals(publish_type_notice)){
                TNotice notice = new TNotice();
                notice.setId(id);
                notice.setNoticeStartTime(dto.getStartTime());
                notice.setNoticeEndTime(dto.getEndTime());
                itNoticeService.updateTNotice(notice);
            } else if (dto.getPublishType().equals(publish_type_high)){
                THighlights light = new THighlights();
                light.setId(id);
                light.setStartTime(dto.getStartTime());
                light.setEndTime(dto.getEndTime());
                tHighlightsMapper.updateTHighlights(light);
            }
        });

        List<Long> classIds = getClassIds(dto);
        // 插入关系表
        List<TPublishClass> saveList = new ArrayList<>();
        dto.getIds().forEach(tid ->{
            classIds.forEach(classId -> {
                TPublishClass c = new TPublishClass();
                c.settId(tid);
                c.setClassId(classId);
                c.setType(dto.getPublishType());
                saveList.add(c);
            });
        });
        tPublishClassMapper.batchInsert(saveList);
    }

    private List<Long> getClassIds(PublishDTO req) {
        return Optional.ofNullable(req)
            .map(a -> {
                // PublishScope 1:班级 2:班牌组
                if (a.getPublishScope().equals(2)) {
                    return classGroupService.listByIds(ListUtils.strToList(a.getScopeIds()))
                        .stream()
                        .map(TClassGroup::getClassIds)
                        .flatMap(b -> ListUtils.strToList(b).stream())
                        .collect(Collectors.toList());
                } else {
                    return ListUtils.strToList(a.getScopeIds());
                }
            }).orElseGet(ArrayList::new);
    }

    /**
     * 修改发布-班级关系
     * 
     * @param tPublishClass 发布-班级关系
     * @return 结果
     */
    @Override
    public int updateTPublishClass(TPublishClass tPublishClass)
    {
        return tPublishClassMapper.updateTPublishClass(tPublishClass);
    }

    /**
     * 批量删除发布-班级关系
     * 
     * @param ids 需要删除的发布-班级关系主键
     * @return 结果
     */
    @Override
    public int deleteTPublishClassByIds(Long[] ids)
    {
        return tPublishClassMapper.deleteTPublishClassByIds(ids);
    }

    /**
     * 删除发布-班级关系信息
     * 
     * @param id 发布-班级关系主键
     * @return 结果
     */
    @Override
    public int deleteTPublishClassById(Long id)
    {
        return tPublishClassMapper.deleteTPublishClassById(id);
    }

    @Override
    public int deleteTPublishClass(TPublishClass tPublishClass) {
        return tPublishClassMapper.deleteTPublishClass(tPublishClass);
    }

    @Override
    public int deleteTPublishClass(Long tId, Integer type) {
        TPublishClass p = new TPublishClass();
        p.settId(tId);
        p.setType(type);
        return this.deleteTPublishClass(p);
    }

    @Override
    public int deleteTPublishClass(List<Long> tIds, Integer type) {
        if (CollectionUtils.isEmpty(tIds)){
            return 0;
        }
        return tPublishClassMapper.deleteByTids(tIds, type);
    }

    @Override
    public List<Long> queryIdsByRoomId(Long roomId, Integer type) {
        TPublishClass pc = new TPublishClass();
        pc.setClassId(roomId);
        pc.setType(type);
        return this.selectTPublishClassList(pc)
            .stream()
            .map(TPublishClass::gettId)
            .collect(Collectors.toList());
    }

    @Override
    public List<Long> queryClassIdsByTid(Long tId, Integer type) {
        TPublishClass pc = new TPublishClass();
        pc.settId(tId);
        pc.setType(type);
        return this.selectTPublishClassList(pc)
            .stream()
            .map(TPublishClass::getClassId)
            .collect(Collectors.toList());
    }

    @Override
    public List<Long> queryClassIdsByTids(List<Long> tIds, Integer type) {
        return tPublishClassMapper.selectListByTids(tIds, type).stream()
            .map(TPublishClass::getClassId)
            .distinct()
            .collect(Collectors.toList());
    }
}
